var select2Config=null;




Vue.component('star', {
	template: `<span style='color:red'>*</span>`,
})
console.info('vue.select2');
//基本用法1
//<select2   url="base/doc?identifier=GSP_Storage_Conditions" v-model="GSP_Storage_Conditions"></select2>
//基本用法2
//<select2 id="fruit" options="[{ id: 1, text: '无需注册证' },{ id:2,text: '注册证商品' },{ id:3,text: '科研试剂1' },{ id:4,text: '科研试剂2' }]"  url="" v-model="w1"></select2>
//动态参数1
// <select2 v-model="data.sampleFromSource" paras="['dept']" :dept="data.sampleTo" url="select2/dsoms/rasClientId.do?ctrl="  style="width:260px"@change="change('data.sampleFromSource')"></select2>
Vue.component('select2', {
	props: ['options', 'url', 'initUrl', 'value'],
	template: `<select> <slot></slot></select>`,
	mounted: function () {
		//console.info("select2 mounted")
		var vm = this;// init select2
		var $s2 = $(this.$el);
		if (this.url != null && this.url != "") {
			select2Helper.initAjax($s2, this.url)
			if (this.value != null && this.value != "") {
				this.setValue(this.value)
			}
		} else if (this.options != null) {
			var opts = eval(this.options)
			$s2.select2({ data: opts });
		}else {
			$s2.select2()
		}
		if (this.value != $s2.val()) {
			$s2.val(this.value)
		}

		$s2.trigger('change').on('change', function () {
			var value = $s2.val();

console.info("change to "+value)

			this.value=value;
			//vm.value=value;
			vm.$emit('update',value) 
			vm.$emit('input', value)
			vm.$emit('change', value)
		})
	},
	watch: {

		//赋值操作
		value: function (value) {
			this.setValue(value)
		},
		options: function (options) {
			// update options
			$(that.$el).empty().select2({ data: options })
		},
		//options扩展，一次加url里面的所有
		initUrl: function (initUrl) {
			var that = this;
			$.ajax({
				url: initUrl,
				async: false,
				type: "POST",
				success: function (options) {
					$(that.$el).empty().select2({ data: options })
				}
			});
		},
		url: function (url) {
			console.info("url:----->" + url)
			if (url != null && url.trim().length > 0) {
				select2Helper.initAjax($(this.$el), url,null,null,false)
			}
		}
	},
	methods: {
		//设值，不通过url
		isSetValueWithOutUrl(){
			if(select2Config==null){
				return false;
			}
			return select2Config.setValueWithOutUrl;
		},

		setValue: function (value) {
			console.info('select2 change:'+value)

			//判断option里面有没有，如果没有则请求数据
			var $s2 = $(this.$el);


			//   var id=$s2.attr("id")
			//   console.info(id)
			//   if(id=="stock_id"){
			// 	  debugger
			//   }
			//   console.info()
			//   console.info("select2:"+$s2.prop("outerHTML"));
			//   console.info("value:"+value);
			// console.info("multiple:"+$s2.attr("multiple"));
			// console.info("value  instanceof Array:"+value  instanceof Array);
			// console.info()

			if ($s2.attr("multiple") == "multiple") {
				if (value instanceof Array) {
					if(this.isSetValueWithOutUrl()){
						for (id of value) {
							if ($s2.find(`option[value='${id}']`).length == 0) {
								$s2.append(`<option value='${id}'>${id}</option>`);
							}
						}
					}else{
					var inStr = "";
					for (id of value) {
						if ($s2.find(`option[value='${id}']`).length == 0) {
							inStr += "," + id;
						}
					}
					if (inStr.length > 0) {
						inStr = inStr.substr(1);
					}
					if (inStr.length > 0 && this.url != null) {

						var searchData={ids:inStr}
						if($s2.attr("paras")!=null){
							var paras=eval($s2.attr("paras"))
							for(var p of paras){
								searchData[p]=$s2.attr(p)
							}
						}


						$.ajax({
							url: this.url ,
							data: searchData,
							async: false,
							type: "POST",
							success: function (data) {
								for (var item of data.items) {
									$s2.append(`<option value='${item.id}'>${item.text}</option>`);
								}
							}
						});
					}
				}
					$(this.$el).val(value)
				}
			} else {

				if (value == null || value == "" || value == "null") {
					$(this.$el).empty()
					$(this.$el).select2("val", " ");

					return;
					value = ""
					$s2.append(`<option value=''></option>`);



				} else if(this.isSetValueWithOutUrl()){
					if ($s2.find(`option[value='${value}']`).length == 0) {
						$s2.append(`<option value='${value}'>${value}</option>`);
					}

				}else if ($s2.find(`option[value='${value}']`).length == 0 && this.url != null) {

						var connectStr = this.url.indexOf("?") != -1 ? "&" : "?"

						// var sValue=value;
						// if((sValue+"").indexOf("+")!=-1){
						// 	sValue =sValue.replace(/\+/g,"%2B")
						// }
						// if((sValue+"").indexOf(" ")!=-1){
						// 	sValue =sValue.replace(/ /g,"%20");
						// }
						// // 1.+ URL 中+号表示空格 %2B
						// 2.空格 URL中的空格可以用+号或者编码 %20						
						// 3./ 分隔目录和子目录 %2F						
						// 4.? 分隔实际的 URL 和参数 %3F						
						// 5.% 指定特殊字符 %25						
						// 6.# 表示书签 %23						
						// 7.& URL 中指定的参数间的分隔符 %26						
						// 8.= URL 中指定参数的值 %3D 

						var searchData={ids:value}
						if($s2.attr("paras")!=null){
							var paras=eval($s2.attr("paras"))
							for(var p of paras){
								searchData[p]=$s2.attr(p)
							}
						}

						$.ajax({
							url: this.url + connectStr ,
							data: searchData,
							async: false,
							type: "POST",
							success: function (data) {
								for (var item of data.items) {
									$s2.append(`<option value='${item.id}'>${item.text}</option>`);
								}
							}
						});
					}
				
				//判断有没有url
				if($(this.$el).attr("cururl")!=null){
					$(this.$el).val(value)//.trigger('change')
				}else {
					$(this.$el).val(value).trigger('change')
				}
				

				// //如果有一次性的方法就调用他
				// var oneTimeMethod=$s2.attr("oneTimeMethod");
				// if(oneTimeMethod!=null){
				// 	debugger
				// 	setTimeout(oneTimeMethod,100);
				// 	console.info(oneTimeMethod)
				// }
				// this.$set(this.$attrs,"onetimemethod",null)
			}



		},
		schange: function () {
			debugger

			Event.$emit('on:select2:changed', $(this.$el));
		}
	},
	destroyed: function () {
		$(this.$el).off().select2('destroy')
	}
});











Vue.component('select2m', {
	props: [
		'options',
		'url',
		'value'
	],
	template: `<select> <slot></slot></select>`,
	mounted: function () {

		console.log("mounted-value:", this.value)

		var vm = this;	// init select2	    	
		var $s2 = $(this.$el);
		if (this.url != null && this.url != "") {
			select2Helper.initAjax($s2, this.url)
			if (this.value != null && this.value != "") {
				this.setValue(this.value)
			}
		} else {
			var opts = eval(this.options)
			$(this.$el).select2({ data: opts });
		}

		$s2.trigger('change').on('change', function () {

			var sel = new Array();
			$(this.$el).find("option").each(function () {
				if ($(this).selected) {
					sel.push($(this).val());
				}
			})

			console.log("element changed sel:", sel)

			vm.$emit('input', sel)
			vm.$emit('change', sel)
		})
	},
	watch: {
		//赋值操作
		value: function (newValue) {
			this.setValue(newValue)
		},
		options: function (options) {
			// update options
			$(this.$el).empty().select2({ data: options })
		},
		url: function (url) {
			if (url != null && url.trim().length > 0) {
				select2Helper.initAjax($(this.$el), url)
			}
		}
	},
	methods: {
		setValue: function (pValue) {
			console.log("multiple-change-value:", pValue)
			var inStr = "";
			for (id of pValue) {
				if ($(this.$el).find(`option[value='${id}']`).length == 0) {
					inStr += "," + id;
				}
			}
			if (inStr.length > 0) {
				inStr = inStr.substr(1);
			}
			if (inStr.length > 0 && this.url != null) {
				var connectStr = this.url.indexOf("?") != -1 ? "&" : "?"
				$.ajax({
					url: this.url + connectStr + "ids=" + inStr,
					data: null,
					async: false,
					type: "POST",
					success: function (data) {
						for (var item of data.items) {
							$(this.$el).append(`<option value='${item.id}'>${item.text}</option>`);
						}
					}
				});
			}
			$(this.$el).val(pValue)
		},
		schange: function () {
			debugger
			console.info("change")
			Event.$emit('on:select2:changed', $(this.$el));
		}
	},
	destroyed: function () {
		$(this.$el).off().select2('destroy')
	}
})